package com.rabbits.ui.dialog.loading;

import android.app.Activity;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

public class RNLoadingDialogModule extends ReactContextBaseJavaModule {

    private final ReactApplicationContext reactContext;
    private final Object object = new Object();
    private LoadingDialog loadingDialog = null;

    public RNLoadingDialogModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext = reactContext;
    }

    @Override
    public String getName() {
        return "RNLoadingDialog";
    }

    /**
     * 显示加载框...
     *
     * @param message 提示信息
     * @param button  取消按钮文案
     * @param promise 点击取消后，回调
     */
    @ReactMethod
    public void show(String message, String button, final Promise promise) {
        showDialog(message, button, new LoadingDialog.OnLoadingListener() {
            @Override
            public void onClick() {
                promise.resolve("cancel");
            }
        });
    }


    @ReactMethod
    public void dismiss() {
        dismissDialog();
    }


    private void showDialog(final String message, final String button,
                            final LoadingDialog.OnLoadingListener listener) {
        dismissDialog();
        final Activity act = getCurrentActivity();
        if (act != null && !act.isFinishing()) {
            act.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (loadingDialog == null) {
                        synchronized (object) {
                            if (loadingDialog == null) {
                                loadingDialog = new LoadingDialog.Builder()
                                        .message(message).listener(button, listener).build(act);
                            }
                        }
                    }
                    if (loadingDialog != null) {
                        loadingDialog.show();
                    }
                }
            });
        }
    }

    private void dismissDialog() {
        if (loadingDialog != null) {
            try {
                synchronized (object) {
                    if (loadingDialog != null) {
                        loadingDialog.dismiss();
                    }
                    loadingDialog = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
